<?php

/**
 * Created by PhpStorm.
 * User: yutongfu
 * Date: 2019/6/23
 * Time: 11:29 AM
 */

class Server
{
    private $serv;

    public function __construct()
    {
        //构建Server对象
        $this->serv = new Swoole\Server('0.0.0.0', 9501, SWOOLE_BASE, SWOOLE_SOCK_TCP);
        //设置运行时参数
        $this->serv->set([
            'work_num' => 1,
        ]);
        //注册事件回调函数
        $this->serv->on('Start', [$this, 'onStart']);
        $this->serv->on('Connect', [$this, 'onConnect']);
        $this->serv->on('Receive', [$this, 'onReceive']);
        $this->serv->on('Close', [$this, 'onClose']);
        $this->serv->start();

    }

    public function onStart($serv)
    {
        echo "Start\n";
    }

    public function onConnect($serv, $fd, $from_id)
    {
        echo "Client {$fd} connect\n";
    }

    public function onClose($serv, $fd, $from_id)
    {
        echo "Client {$fd} close connect\n";
    }

    public function onReceive(swoole_server $serv, $fd, $form_id, $data)
    {
        echo "Get Message From Client {$fd}:{$data}\n";
        foreach ($serv->connections as $client) {
            if ($fd != $client) {
                $serv->send($client, $data);
            }
        }
    }

}

$server = new Server();